package com.deepq.controller;



import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullResult;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * description: add a description [描述信息]
 *
 * @author : zp
 * @date 2024/4/19
 */
@Controller
public class GitController {
    private static final Logger logger = LoggerFactory.getLogger(GitController.class);
    private static Git git;
    private static Repository localRepo;


    // git仓库地址
    private static String rpsUrl = "https://gitee.com/zpeter/zptest";
    //git分支名称
    private static String branchName = "master";
    // git项目名字
    private static String projectName = "sm4Util";
    //git登录名字
    private static String userName = "568849059@qq.com";
    //git登录密码
    private static String password = "zp@89218243";
    // git本地路径
    private static String localRootPath = "D:\\officeWork\\deepq\\tool-work";

    public static CredentialsProvider createCredential(String userName, String password) {
        return new UsernamePasswordCredentialsProvider(userName, password);
    }

    public static void main(String[] args) {
        GitSync();
    }
    public static String GitSync(){
        logger.info("Git Sync: start..."+getCurrentTime());
        boolean isSuccess = false;
        UsernamePasswordCredentialsProvider provider =
                new UsernamePasswordCredentialsProvider(userName, password);

        try {
            logger.info("============localPath==========" + getLocalPath());
            localRepo = new FileRepository(getLocalPath() + "/.git");
            git = new Git(localRepo);
            File localPathFile = new File(getLocalPath());
            if (!localPathFile.exists()) {
                Git git = GitClone(rpsUrl, branchName, getLocalPath(),provider);
                if (git != null){
                    isSuccess = true;
                }
            } else {
                isSuccess = GitPull(branchName,provider);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            logger.info("Git Sync: end..."+getCurrentTime());
            return "git sync failed";
        }finally{
            logger.info("Git Sync: end..."+getCurrentTime());
        }

        if (isSuccess){
            return "git sync success";
        }
        return "git sync failed";
    }

    /**
     * 获取本地路径
     * @return
     */
    private static String getLocalPath(){
        return localRootPath + File.separator + projectName;
    }

    /**
     * 获取当前时间
     * @return
     */
    private static String getCurrentTime(){
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        return formatter.format(date);
    }

    /**
     * 执行GitClone
     */
    private static Git GitClone(String gitUrl, String branch, String localPath, UsernamePasswordCredentialsProvider credentialsProvider) throws Exception {
        return Git.cloneRepository().setURI(gitUrl).setBranch(branch).setDirectory(new File(localPath)).setCredentialsProvider(credentialsProvider).call();
    }

    /**
     * 执行GitPull
     */
    private static boolean GitPull(String branch, UsernamePasswordCredentialsProvider credentialsProvider) throws Exception {
        // 强制stash 保证不会冲突
        git.stashCreate();

        //TODO 更多命令
        //git.pull();
        //git.add();
        //git.push();
        //git.merge();

        PullResult result = git.pull().setRemoteBranchName(branch).setCredentialsProvider(credentialsProvider).call();
        return result.isSuccessful();
    }
}


